<template>
  <div class="m-pageView">
    <div class="m-searchPanel">
      <div class="layout-1"><span class="leftLine"></span>查询条件</div>
      <div class="layout-2">
        <el-form :model="searchForm" :inline="true">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item class="input-with-select">
                <el-input placeholder=" " v-model.trim="searchForm.value" clearable>
                  <el-select v-model="searchForm.type" slot="prepend" placeholder="请选择" class="selectInputType"
                             clearable>
                    <el-option label="姓名" value="1"></el-option>
                    <el-option label="手机号" value="2"></el-option>
                    <el-option label="电子邮箱" value="3"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col class="searchBtns" :span="6" :offset="12">
              <el-button type="primary" icon="el-icon-search" @click="search" :loading="dataListLoading">查询
              </el-button>
              <el-button type="primary" plain icon="el-icon-refresh" @click="reset">重置</el-button>
          </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="m-dataLayout">
      <div class="m-searchListPanel">
        <div class="layout-1"><span class="leftLine"></span>信息列表</div>
        <div class="layout-2">
          <el-button type="text" icon="el-icon-plus" @click="addRowData.show = true"
                     v-if="buttonAuthority.lead_filter && buttonAuthority.lead_filter.create">新建
          </el-button>
          <el-button type="text" icon="el-icon-upload" @click="uploadDatas.show=true"
                     v-if="buttonAuthority.lead_filter && buttonAuthority.lead_filter.upload">上传
          </el-button>
        </div>
      </div>
      <div class="m-filterPageData">
        <div class="m-dataList">
          <el-table
            :data="dataList"
            style="width: 100%"
            v-loading="dataListLoading"
            element-loading-text="loading..."
            ref="dataList"
            max-height="600"
          >
            <el-table-column
              prop="type"
              label="字段"
              width="120">
              <template slot-scope="scope">
                <span>{{scope.row.type | formatType}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="value"
              label="字段值"
              width="300">
            </el-table-column>
            <el-table-column
              prop="createUser"
              label="创建人"
              width="120">
            </el-table-column>
            <el-table-column
              prop="createTimeStr"
              label="创建时间">
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="buttonAuthority.lead_filter && buttonAuthority.lead_filter.delete"
              align="center"
              fixed="right"
              width="110">
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" size="small"
                           @click="deleteRowData(scope.row.id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="m-pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes=pagination.pageSizeList
            :current-page=pagination.pageNo
            :page-size=pagination.pageSize
            layout="total, sizes, prev, pager, next"
            :total=pagination.total>
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="创建LEADS过滤名单" :visible.sync="addRowData.show" width="377px" class="m-dialog"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="clearAddRowDataForm">
      <el-form :model="addRowData.form" :inline="true" ref="refAddRowDataForm" :rules="addRowData.rules"
               label-position="left" label-width="80px">
        <el-form-item label="字段" prop="type">
          <el-select v-model="addRowData.form.type">
            <el-option label="姓名" value="1"></el-option>
            <el-option label="手机号码" value="2"></el-option>
            <el-option label="电子邮箱" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字段值" prop="value" class="last">
          <el-input v-model="addRowData.form.value" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRowData.show = false">取消</el-button>
        <el-button type="primary" @click="addRowDataSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="上传LEAD过滤名单" :visible.sync="uploadDatas.show" width="400px" class="m-dialog"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="closeUploadDialog">
      <el-form :model="uploadDatas.form" :rules="uploadDatas.rules" ref="refUploadDatas">
        <el-form-item prop="fileName">
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">上传文件</el-col>
            <el-col :span="13">
              <el-input :disabled="true" v-model="uploadDatas.form.fileName" placeholder="未选择文件"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-upload
                :multiple="false"
                accept=""
                action="/"
                :on-change="handleUpladFileSuccess"
                :show-file-list="false"
                :auto-upload="false">
                <el-button type="text" class="link-btn">文档上传</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">下载模板</el-col>
            <el-col :span="13">
              <el-input value="下载模板" :disabled="true"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-button type="text" class="link-btn"><a href="/static/xlsTMP/Create_FilterList_of_Lead.xlsx"
                                                         download>点击下载</a></el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div class="dialog-tipWords">
        <div class="tipTitle">提示：</div>
        <div class="tipContent">
          1. 不填写的栏位表示不更新<br>
          2. 单次批量上传上限为1000条
        </div>
      </div>
      <div slot="footer">
        <el-button @click="uploadDatas.show = false">取消</el-button>
        <el-button type="primary" @click="uploadDatasSubmit">提交</el-button>
      </div>
    </el-dialog>
    <Comp-Upload-Dialog :show.sync="showUploadDialog" :step.sync="showUploadDialogStep"></Comp-Upload-Dialog>
  </div>
</template>

<script>
  import * as Utils from '@/utils'
  import * as LeadsAPI from '@/Api/lead';
  import CompUploadDialog from '@/components/CompUploadDialog.vue'
  import {mapGetters} from 'vuex'
  import ElCol from "element-ui/packages/col/src/col";
  export default {
    name: 'LeadsFilterList',
    data () {
      return {
        searchForm: {
          type: '',
          value: ''
        },
        copySearchForm: null,
        pagination: Utils.commonPagination(),
        dataList: [],
        dataListLoading: false,
        addLoading: false,
        showUploadDialog: false,//显示上传进度弹窗
        showUploadDialogStep: 'ing',//显示上传进度弹窗 -进度
        addRowData: {
          show: false,
          form: {
            type: '',
            value: ''
          },
          rules: {
            type: [
              {required: true, trigger: 'blur', message: '内容不能为空'}
            ],
            value: [
              {required: true, trigger: 'blur', message: '内容不能为空'},
            ]
          }
        },
        uploadDatas: {
          show: false,
          form: {
            file: null,
            fileName: '',
          },
          rules: {
            fileName: [
              {required: true, trigger: 'blur', message: '请上传文件'}
            ]
          }
        },
        ajaxSearchParams:{},
      }
    },
    filters: {
      formatType(val) {
        if (val == '1') {
          return '姓名';
        } else if (val == '2') {
          return '手机号';
        } else if (val == '3') {
          return '电子邮箱';
        } else {
          return '未匹配';
        }
      }
    },
    components: {
      ElCol,
      CompUploadDialog,
    },
    computed: {
      ...mapGetters([
        'buttonAuthority',
      ]),
    },
    methods: {
      clearAddRowDataForm() {
        this.$refs.refAddRowDataForm.resetFields();
      },
      deleteRowData(id){
        this.$confirm('确认删除该条数据?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            LeadsAPI.leadsFilterDelete({
              id
            })
              .then(res => {
                if (res.code != 0) {
                  this.$notify({
                    title: '温馨提示',
                    message: res.msg,
                    type: 'warning'
                  })
                  return;
                }
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                if (this.pagination.pageNo == 1) {
                  this.queryList();
                } else {
                  this.pagination.pageNo = 1;
                }
              })
              .catch(error => {
                console.log(error)
              })
          }).catch(() => {
        });
      },
      addRowDataSubmit() {
        this.$refs.refAddRowDataForm.validate((flg) => {
          if (!flg) {
            return;
          }
          this.addLoading = true;
          LeadsAPI.leadsFilterCreate(this.addRowData.form)
            .then(res => {
              this.addLoading = false;
              if (res.code != 0) {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warning'
                })
                return;
              }
              this.$message({
                message: '新建成功',
                type: 'success'
              });
              this.addRowData.show = false;
              if (this.pagination.pageNo == 1) {
                this.queryList();
              } else {
                this.pagination.pageNo = 1;
              }
            })
            .catch(error => {
              this.addLoading = false;
              console.log(error)
            })
        })
      },
      uploadDatasSubmit() {
        this.$refs.refUploadDatas.validate(flg => {
          if (!flg) {
            return;
          }
          this.showUploadDialog = true;
          this.showUploadDialogStep = 'ing';
          Utils.xlsxToJson(this.uploadDatas.form.file, ['type', 'value'])
            .then(res => {
              if (res.length > 1000) {
                this.showUploadDialog = false;
                this.$alert('上传数据不能超过一千条', '温馨提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$message({
                      type: 'warning',
                      message: `action: ${ action }`
                    });
                  }
                });
                return;
              }
              this.upLoadDatesService(res)
                .then(res => {
                  this.$notify({
                    title: '温馨提示',
                    message: '数据上传成功',
                    type: 'success'
                  })
                  this.showUploadDialogStep = 'success';
                  if (this.pagination.pageNo == 1) {
                    this.queryList();
                  } else {
                    this.pagination.pageNo = 1;
                  }
                  this.uploadDatas.show = false;
                })
                .catch(error => {
                  if (error) {
                    this.showUploadDialogStep = 'exception';
                  } else {
                    this.showUploadDialog = false;
                  }
                })
            })
            .catch(error => {
              this.showUploadDialog = false;
              this.$message({
                message: error,
                type: 'warning'
              });
            })
        })
      },
      upLoadDatesService(array){
        return new Promise((resolve, reject) => {
          LeadsAPI.leadsFilterUpload({
            data: JSON.stringify(array)
          })
            .then(res => {
              if (res.code != 0) {
                this.$notify({
                  type: 'warning',
                  title: '温馨提示',
                  message: res.msg,
                })
                reject(true);
                return;
              }
              if (res.data && res.data.length > 0) {
                Utils.JsonToXlsx(res.data, {
//                    'typeStr': '字段 (必填)',
                  'type': '字段 (必填)',
                  'value': '字段值 (必填)',
                  'remark': '错误描述'
                })
                  .catch(error => {
                    this.$notify({
                      type: 'warning',
                      title: '温馨提示',
                      message: error,
                    })
                  })
              }
              resolve();
            })
            .catch(error => {
              console.log(error)
              reject(false);
            })
        })
      },
      handleUpladFileSuccess(file){
        this.uploadDatas.form.file = file;
        this.uploadDatas.form.fileName = file.raw.name
      },
      closeUploadDialog(){
        this.uploadDatas.form.file = null;
        this.uploadDatas.form.fileName = '';
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size;
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleCurrentChange(index) {
        this.pagination.pageNo = index;
        this.queryList();
      },
      search() {
        this.ajaxSearchParams = Utils.searchParamsFormat(this.searchForm);
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      createListParams() {
        return Object.assign(this.ajaxSearchParams, {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        })
      },
      queryList(){
        this.dataListLoading = true;
        if (this.$refs.dataList) {
          this.$refs.dataList.bodyWrapper.scrollTop = 0;
        }
        LeadsAPI.leadFilterQuery(this.createListParams())
          .then(res => {
            this.dataListLoading = false;
            if (res.code != 0) {
              this.$notify({
                title: '温馨提示',
                message: res.msg,
                type: 'warning'
              })
              return;
            }
            this.dataList = res.data.data;
            this.pagination.total = res.data.total;
          })
          .catch(error => {
            this.dataListLoading = false;
            console.log(error)
          })
      },
      reset() {
        this.searchForm = Object.assign({}, this.copySearchForm);
      },
    },
    created(){
      this.copySearchForm = Object.assign({}, this.searchForm);
      this.search();
    }
  }
</script>

<style scoped lang="scss">
  @import "../../scss/variables";
</style>
